
/**
 * use
 * npm run updateVersion 
 * npm run updateVersion 1.0.0
 */

const fs = require('fs')
const { resolve } = require('path')
// const toml = require('smol-toml')
const packageJsonPath = resolve(__dirname, '../package.json')
const tauriConfJsonPath = resolve(__dirname, `../src-tauri/tauri.conf.json`)
const CargoTomlPath = resolve(__dirname, `../src-tauri/Cargo.toml`)
function updatePackageJson (version) {
    const packageJson = require(packageJsonPath)
    if (!version) {
        const versionList = packageJson.version.split('.')
        versionList[2] = parseInt(versionList[2]) + 1 // 修订号+1
        version = versionList.join('.')
    }
    packageJson.version = version
    fs.writeFileSync(
        './package.json',
        JSON.stringify(packageJson, null, 2)
    )
    return version
}
function updateTauriConfigJsonVersion (version) {
    const tauriConfig = require(tauriConfJsonPath)
    tauriConfig.version = version
    fs.writeFileSync(
        tauriConfJsonPath,
        JSON.stringify(tauriConfig, null, 2)
    )
}
/**
 * 有bug，更新后结构注释会被去除，不方便
 * @param {*} version 
 */
// function updateCargoTomlVersion (version) {
//     const tauriConfigText = fs.readFileSync(CargoTomlPath, 'utf-8').toString()
//     const tauriConfig = toml.parse(tauriConfigText)
//     tauriConfig.package.version = version
//     fs.writeFileSync(
//         CargoTomlPath,
//         toml.stringify(tauriConfig, {
//             maxDepth: 5
//         })
//     )
// }
// 自动更新版本号（遵循 semver）
function updateVersion () {
    let version = process.argv[2]
    version = updatePackageJson(version)

    updateTauriConfigJsonVersion(version)
    // updateCargoTomlVersion(version)
    console.log(`版本号已更新为: ${version}`)
}

updateVersion()